import { formatTime } from '../../utils/util';
let mixinList = require('../../common/mixinList');
Page({
    behaviors: [mixinList],
    data: {
        navInfo: null,
        bannerList: [], //轮播图列表
        notice: null, //通知公告
        navList: [], //导航栏列表
        navCurrent: 0, //当前导航轮播索引
        today: [], //今日
        turnover: 0, //今日成交量
        rounds: '一', //当前场次
        time: 0, //当前场次交易结束倒计时时间
        timeData: {}, //倒计时格式化后的时间
        nextTimeLabel: '', //下场开始时间
        real_list: [], //实时成交数据
        upAndDown: [], //涨跌列表
        upAndDownTime: '', //涨跌模块的实时时间
        preferentialList: [], //特惠商品列表
        qualityList: [], //品质商品列表
        videoList: [], //视频商品列表
        showAddCartPopup: false, //展示加入购物车弹窗
        addCartCurrent: null, //加入购物车商品信息
        supplierList: [], //推荐供应商列表
        classList: [], //tab分类列表
        tab_active: 0, //tab分类列表选中项
        reqUrl: '/api/product/items', //tab分类产品请求url
        usePrivateMethod: true,
        pageScrollDistance: 0, //tab每次吸顶滚动的距离
        enableTabScroll: false,
    },
    timeOutId: '', //定时任务定时器，页面销毁时清除
    onLoad: function (options) {
        try {
            if (options.scene != undefined) {
                //绑定关系
                let scene = unescape(options.scene);
                var index = scene.lastIndexOf('=');
                scene = scene.substring(index + 1, scene.length);
                this.redirect_login(scene);
            }
            if (options.uid) {
                //页面分享携带uid绑定关系
                this.redirect_login(options.uid);
            }
        } catch (error) {}
        this.setData({
            navInfo: getApp().globalData.navInfo,
        });
        this.getBanner();
        this.getNotice();
        this.getNav();
        this.getBusiness();
        this.getTurnover();
        this.timedTask(
            {
                //参数的说明
                interval: 1, //间隔天数，间隔为整数
                runNow: false, //是否立即运行
                time: '00:00:00', //执行的时间点 时在0~23之间
            },
            this.getBusiness
        );
    },
    onShow() {
        this.getUpAndDown(true);
    },
    onReady() {
        getApp().watchGlobalData('cartCheckNum', value => {
            let tabbar = this.selectComponent('#tabbar'); // 页面获取自定义组件实例
            tabbar.setCartCheckNum(value); // 通过实例调用组件事件
        });
    },
    /**获取轮播图 */
    getBanner() {
        this.request(
            {
                url: '/api/index/banner?from=index',
                login: false,
            },
            res => {
                this.setData({ bannerList: res.data });
            }
        );
    },
    /**点击轮播图跳转链接 */
    toWebView({ mark }) {
        if (mark.link) wx.navigateTo({ url: mark.link });
    },
    /**获取导航 */
    getNav() {
        this.request(
            {
                url: '/api/index/nav',
                login: false,
            },
            res => {
                this.setData({ navList: res.data });
            }
        );
    },
    /**点击导航 */
    toTradingHall(e) {
        const { index } = e.currentTarget.dataset;
        wx.reLaunch({
            url: `/pages/trading_hall/index?id=${this.data.navList[index].link}`,
        });
    },
    /**导航轮播切换 */
    navSwiperChange(event) {
        this.setData({
            navCurrent: event.detail.current,
        });
    },
    /**获取通知公告 */
    getNotice() {
        this.request(
            {
                url: '/api/article/detail?article_id=11',
                login: false,
            },
            res => {
                res.data.article_content.content = res.data.article_content.content
                    .replace(/<([^>]+?)([^>]*?)>/gi, '')
                    .replaceAll('&nbsp;', '');
                this.setData({
                    notice: {
                        title: res.data.title,
                        content: res.data.article_content.content,
                    },
                });
            }
        );
    },
    /**获取交易时间段 */
    getBusiness() {
        this.request(
            {
                url: '/api/index/config?type=2',
                login: false,
            },
            res => {
                const orderPeriod = res.data;
                const today = formatTime(new Date())
                    .slice(0, 10)
                    .replaceAll('-', '/');
                const endTime = new Date(
                    today + ' ' + orderPeriod.trade_ltime
                ).getTime();
                let remainingTime = endTime - Date.now(); //单天第一场结束时间戳

                //获取下场开始时间戳
                const nextTime = endTime + orderPeriod.stop_trade * 60 * 1000;
                //格式化下场开始交易时间
                const nextTimeLabel = formatTime(new Date(nextTime)).slice(
                    11,
                    16
                );

                /**大于0-->单天第一次交易时间段 */
                if (remainingTime > 0) {
                    this.setData({
                        time: remainingTime,
                        nextTimeLabel,
                        rounds: '一',
                    });
                } else {
                    /**判断是否处于禁止交易时间段，处于显示第一场倒计时0，不处于则为第二场，计算单日23:59:59的倒计时，提示设置下场交易时间为0:0 */
                    if (Date.now() < nextTime) {
                        //禁止交易时间段
                        this.setData({ time: 0.1, nextTimeLabel });
                        //新建定时任务，禁止交易时间段结束后，重新你请求接口
                        this.timedTask(
                            {
                                //参数的说明
                                interval: 1, //间隔天数，间隔为整数
                                runNow: false, //是否立即运行
                                time: nextTimeLabel + ':00', //执行的时间点
                            },
                            this.getBusiness
                        );
                    } else {
                        //计算23:59:59离现在的时间戳
                        const secondEndTime = new Date(
                            today + ' 23:59:59'
                        ).getTime();
                        let secondRemainingTime =
                            secondEndTime + 1000 - Date.now(); //单天第二场结束时间戳
                        this.setData({
                            time: secondRemainingTime,
                            nextTimeLabel: '0:00',
                            rounds: '二',
                        });
                    }
                }
            }
        );
    },
    /**定时任务，页面开启状态每天凌晨0:00执行 */
    timedTask(config, func) {
        config.runNow && func();
        const nowTime = new Date().getTime();
        const timePoints = config.time.split(':').map(i => parseInt(i));
        let recent = new Date().setHours(...timePoints);
        recent >= nowTime || (recent += 24 * 3600000);
        this.timeOutId = setTimeout(() => {
            func();
            clearTimeout(this.timeOutId);
            setInterval(func, config.interval * 3600000);
        }, recent - nowTime);
    },
    //获取涨跌
    getUpAndDown() {
        //获取实时时间
        const hours = new Date().getHours().toString().padStart(2, '0');
        const minutes = new Date().getMinutes().toString().padStart(2, '0');
        this.setData({ upAndDownTime: `${hours}:${minutes}` });
        this.request(
            {
                url: '/api/index/rateByCate',
                login: false,
            },
            res => {
                res.data.forEach(item => {
                    if (Number(item.change_rate) === 0) {
                        item.isUp = false;
                        item.upAndDownPrice = 0;
                        item.change_rate = '-' + item.change_rate;
                    } else {
                        let upAndDownPrice = Number(
                            (
                                item.today_price - Number(item.yesterday_price)
                            ).toFixed(2)
                        );
                        item.isUp = upAndDownPrice > 0;
                        item.upAndDownPrice = Math.abs(upAndDownPrice);
                    }
                });
                this.setData({ upAndDown: res.data });
            }
        );
    },
    //获取成交量
    getTurnover(reqNext = true) {
        const today = formatTime(new Date()).slice(0, 10).split('-');
        this.request(
            {
                url: '/api/index/sales',
                login: false,
            },
            res => {
                this.setData({
                    turnover: res.data.sales,
                    today,
                    real_list: res.data.real_list,
                });
            },
            null,
            () => {
                reqNext && this.getPreferentialGoods();
            }
        );
    },
    /**获取特惠商品 */
    getPreferentialGoods() {
        this.request(
            {
                url: '/api/product/index',
                data: {
                    special_offer: '1',
                    limit: 10,
                },
            },
            res => {
                this.setData({ preferentialList: res.data });
            },
            null,
            () => {
                this.getRecommendGoods();
            }
        );
    },
    /**获取品质商品 */
    getRecommendGoods() {
        this.request(
            {
                url: '/api/product/index',
                data: {
                    type: '2',
                    limit: 6,
                },
            },
            res => {
                this.setData({ qualityList: res.data });
            },
            null,
            () => {
                this.getVideoGoods();
            }
        );
    },
    /**获取视频商品 */
    getVideoGoods() {
        this.request(
            {
                url: '/api/product/index',
                data: {
                    type: '3',
                    limit: 4,
                },
            },
            res => {
                this.setData({ videoList: res.data });
            },
            null,
            () => {
                this.getSupplier();
            }
        );
    },
    /**获取推荐供应商 */
    getSupplier() {
        this.request(
            {
                url: '/api/supplier/hot',
                login: false,
                data: { limit: 6 },
            },
            res => {
                this.setData({ supplierList: res.data });
            },
            null,
            () => {
                this.getClassList();
            }
        );
    },
    /**前往供应商列表 */
    toMoreSupplier() {
        wx.switchTab({
            url: '/pages/supplier/index',
        });
    },
    /**点击加入购物车 */
    openAddcartPopup(e) {
        const { info } = e.currentTarget.dataset;

        if (info.sku === 0)
            return wx.showToast({
                title: '该商品已售空',
                icon: 'none',
            });
        const { imgHost } = this.data;
        const addCartCurrent = {
            product_img: imgHost + info.product_img,
            product_name: info.product_name,
            product_price: info.product_price,
            sku: info.sku,
            unit: info.unit,
            supplier_id: info.supplier.supplier_id,
            supplier_name: info.supplier.title,
            level: info.level,
            norm: info.norm,
            product_id: info.product_id,
            sell_num: info.sell_num,
        };

        this.setData({
            addCartCurrent,
            showAddCartPopup: true,
        });
    },
    /**前往更多商品列表 */
    toMoreGoods(e) {
        const { type } = e.currentTarget.dataset;
        wx.navigateTo({
            url: '/pages/home_goods/index?type=' + type,
        });
    },
    /**获取全部分类 */
    getClassList() {
        this.request(
            {
                url: '/api/product/cate',
                login: false,
            },
            res => {
                this.setData({ classList: res.data });
                this.getList(true);
            }
        );
    },
    //获取tabs吸顶距离
    getPageScrollDistance() {
        //获取tabs头部距离顶部的距离，切换选项时移动到局部内容顶部
        this.getRect(this, '.space_class_tabs').then(res => {
            const { navInfo } = this.data;
            this.setData({
                pageScrollDistance: res.top - navInfo.top - navInfo.height - 10,
            });
        });
    },
    /**分类切换 */
    onClassChange(e) {
        this.setData({ tab_active: e.detail.index, enableTabScroll: true });
        this.getList(true);
    },
    getParamsData() {
        //页面特殊的请求参数，需要时在页面内覆盖此方法，默认返回{}
        const { classList, tab_active } = this.data;
        let params = { cate_id: classList[tab_active].cate_id, limit: 15 };
        return params;
    },
    privateMethod(refresh, res) {
        //页面使用此Behavior私有方法,需要时在页面内覆盖此方法
        return new Promise(resolve => {
            resolve(res.data);
            if (this.data.pageScrollDistance) {
                refresh && this.tabScrollToTop();
            } else {
                this.delay(() => {
                    this.getPageScrollDistance();
                });
            }
        });
    },
    tabScrollToTop() {
        this.data.enableTabScroll &&
            wx.pageScrollTo({
                scrollTop: this.data.pageScrollDistance,
                duration: 150,
                success: () => {
                    this.setData({ enableTabScroll: false });
                },
            });
    },
    //前往商品列表页
    toGoodsList({ mark }) {
        const { index, collect } = mark;
        if (index == undefined) return;
        let info = this.data.list[index];
        if (collect) {
            //关注
            return this.request(
                {
                    url: '/api/user/collect/collect',
                    method: 'POST',
                    data: {
                        status: info.collected ? 0 : 1,
                        can_id: info.product_common_id,
                        type: '1',
                    },
                },
                () => {
                    wx.showToast({
                        title: info.collected ? '取消成功' : '收藏成功',
                        icon: 'success',
                    });
                    this.setData({
                        ['list[' + index + '].collected']: info.collected
                            ? 0
                            : 1,
                    });
                }
            );
        }
        wx.navigateTo({
            url: `/pages/hall_goods/index?cate_id=${this.data.list[index].cate_id}&product_common_id=${this.data.list[index].product_common_id}`,
        });
    },
    onCountDownChange({ detail }) {
        detail.days = detail.days.toString().padStart(2, '0');
        detail.hours = detail.hours.toString().padStart(2, '0');
        detail.minutes = detail.minutes.toString().padStart(2, '0');
        detail.seconds = detail.seconds.toString().padStart(2, '0');
        this.setData({ timeData: detail });
    },
    //获取节点位置信息
    getRect(context, selector) {
        return new Promise(function (resolve) {
            wx.createSelectorQuery()
                .in(context)
                .select(selector)
                .boundingClientRect()
                .exec(function (rect) {
                    if (rect === void 0) {
                        rect = [];
                    }
                    return resolve(rect[0]);
                });
        });
    },
    /**确认搜索 */
    toSearch({ detail }) {
        detail &&
            wx.navigateTo({
                url: '/pages/hall_goods/index?keyWords=' + detail,
            });
    },
    refresh() {
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 0,
        });
        this.getBanner();
        this.getNotice();
        this.getBusiness();
        this.getTurnover(false);
        this.timedTask(
            {
                //参数的说明
                interval: 1, //间隔天数，间隔为整数
                runNow: false, //是否立即运行
                time: '00:00:00', //执行的时间点 时在0~23之间
            },
            this.getBusiness
        );
    },
    //点击分享
    onShareAppMessage({ from }) {
        const promise = new Promise(resolve => {
            let options, title;
            if (from === 'button') {
                //转发商品详情
                const { tab_active, tabs, imgHost } = this.data;
                this.delay(() => {
                    options = `/pages/good_detail/index?id=${
                        tabs[tab_active].data[this.data.shareCurrent].product_id
                    }`;
                    if (this.data.userInfo)
                        options += `&uid=${this.data.userInfo.uid}`;
                    title = `向你推荐了${
                        tabs[tab_active].data[this.data.shareCurrent]
                            .product_name
                    }，快点击查看吧！`;

                    resolve({
                        path: options,
                        title,
                        imageUrl:
                            imgHost +
                            tabs[tab_active].data[this.data.shareCurrent]
                                .product_img,
                    });
                }, 200);
            } else {
                //分享首页
                options = '/pages/index/index?x=x';
                if (this.data.userInfo)
                    options += `&uid=${this.data.userInfo.uid}`;
                resolve({
                    path: options,
                    title: '向你推荐了云花街，快点击查看吧！',
                });
            }
        });

        return {
            promise,
        };
    },
    onUnload() {
        clearTimeout(this.timeOutId);
    },
});
